#include "packet_sql.h"
namespace SQL
{
    std::string PacketSQL::buildPacketQuerySQL(const Tshark::QueryConditon &condition)
    {
        // note: 拼接sql语句的方式
        std::stringstream ss;
        ss << "SELECT * FROM t_packets";
        std::vector<std::string> conditionList;

        if (condition.ip != "")
        {
            std::string cond_ip = fmt::format("(src_ip GLOB \"{}\" or dst_ip GLOB \"{}\")", condition.ip, condition.ip);
            conditionList.emplace_back(cond_ip);
        }

        if (condition.port != 0)
        {
            std::string cond_port = fmt::format("(src_port = {} or dst_port = {})", condition.port, condition.port);
            conditionList.emplace_back(cond_port);
        }

        if (condition.location != "")
        {
            std::string cond_location = fmt::format("(src_location GLOB \"{}\" or dst_location GLOB \"{}\")", condition.location, condition.location);
            conditionList.emplace_back(cond_location);
        }

        if (condition.mac != "")
        {
            std::string cond_mac = fmt::format("(src_mac GLOB \"{}\" or dst_mac GLOB \"{}\")", condition.mac, condition.mac);
            conditionList.emplace_back(cond_mac);
        }

        if (condition.proto != "")
        {
            std::string proto = condition.proto;
            for (auto &c : proto)
            {
                c = std::toupper(c);
            }
            std::string cond_proto = fmt::format("protocol GLOB \"{}\"", proto);
            conditionList.emplace_back(cond_proto);
        }
        if (!conditionList.empty())
        {
            ss << " WHERE ";
            for (ssize_t i = 0; i < conditionList.size(); ++i)
            {
                if (i != conditionList.size() - 1)
                {
                    ss << conditionList[i] << " AND ";
                }
                else
                {
                    ss << conditionList[i] << ";";
                }
            }
        }
        std::string sql = ss.str();
        LOG_F(INFO, "[BUILD SQL]: %s", sql.c_str());
        return sql;
    }
}